package br.ucb.sigplan.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.ucb.sigplan.beans.Conteudo;
import br.ucb.sigplan.beans.ConteudoTurma;
import br.ucb.sigplan.connection.FactoryCon;
import br.ucb.sigplan.dao.ConteudoTurmaDAO;
import br.ucb.sigplan.exception.DAOException;

public class ConteudoTurmaDAOImpl implements ConteudoTurmaDAO {
	private final String SQL_INSERT = "insert into conteudo_turma (idconteudo,idturma) values (?,?);";
	private final String SQL_SEARCHCONTEUDO = "select c.descricao, c.idconteudo from conteudo c, turma t, " +
			"conteudo_turma ct where t.idturma = ct.idturma and c.idconteudo = ct.idconteudo and t.idturma = ?;";
	private final String SQL_DELETE = "delete from conteudo_turma where idconteudo = ? and idturma = ?";

	public List<Conteudo> findConteudoByTurma(Integer idturma) throws DAOException {
		List<Conteudo> conteudos = new ArrayList<Conteudo>();
		Connection con = FactoryCon.getInstance().createConnection();
		PreparedStatement instrucao = null;
		ResultSet set = null;
		Conteudo conteudo;
		try {
			instrucao = con.prepareStatement(SQL_SEARCHCONTEUDO);
			instrucao.setInt(1, idturma);
			set = instrucao.executeQuery();
			while (set.next()) {
				conteudo = new Conteudo();
				putConteudo(set, conteudo);
				conteudos.add(conteudo);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new DAOException("erroAtualizacao");
		}
		return conteudos;
	}
	
	private void putConteudo(ResultSet set, Conteudo conteudo) throws SQLException {
		conteudo.setIdConteudo(set.getInt("idconteudo"));
		conteudo.setDescricao(set.getString("descricao"));
	}


	public void insert(ConteudoTurma conteudoTurma) throws DAOException {
		Connection con = FactoryCon.getInstance().createConnection();
		PreparedStatement instrucao = null;
		try {
			instrucao = con.prepareStatement(SQL_INSERT);
			instrucao.setInt(1, conteudoTurma.getConteudo().getIdConteudo());
			instrucao.setInt(2, conteudoTurma.getTurma().getIdTurma());
			instrucao.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new DAOException("erroInsercao");
		} finally {
			FactoryCon.closeConnection(con, instrucao);
		}
	}

	public void delete(ConteudoTurma conteudoTurma) throws DAOException {
		Connection con = FactoryCon.getInstance().createConnection();
		PreparedStatement instrucao = null;
		try {
			instrucao = con.prepareStatement(SQL_DELETE);
			instrucao.setInt(1, conteudoTurma.getConteudo().getIdConteudo());
			instrucao.setInt(2, conteudoTurma.getTurma().getIdTurma());
			instrucao.executeUpdate(); 
		} catch (SQLException e) {
			e.printStackTrace();
			throw new DAOException("erroDelecao");
		} finally {
			FactoryCon.closeConnection(con, instrucao);
		}
	}

}
